package com.welikemovies;

import java.awt.EventQueue;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.awt.Choice;
import javax.swing.JLabel;
import java.awt.Font;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;

import javax.swing.JPanel;
import javax.swing.JScrollPane;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import java.awt.CardLayout;
import javax.swing.JPasswordField;
import javax.swing.JCheckBox;
import java.awt.Component;
import javax.swing.ListModel;
import javax.swing.border.TitledBorder;


public class ApplicationWindow {
	
	public boolean isAdmin;
	public int customerID;
	
	private JFrame frame;
	private JMenuBar menuBar = new JMenuBar();
	private JTextField textField;
	private static DatabaseHandler dbHandler;
	private DefaultListModel movieModel;
	private DefaultListModel movieModel2;
	private JList movieList;
	private JList movieList2;
	private DefaultListModel resModel;
	private JList resList;	
	private DefaultListModel avalibleModel;
	private DefaultListModel copyModel;
	private JList avalibleList;
	private JList copyList;
	private static JLabel lblStarring;
	private static JLabel lblAwardsWon;
	
	final static String LOGINPANEL = "Card with the Login";
	final static String SIGNUPPANEL = "Card with the Account Creation";
	final static String EDITINFOPANEL = "Card with the Edit Customer Information";
	final static String MOVIESPANEL = "Card with the Movies";
	final static String EDITMOVIESPANEL = "Card with the Edit Movies";
	final static String RESERVATIONSPANEL = "Card with the Reservations";
	private JTextField text_username;
	private JTextField textField_1;
	private JTextField textField_2;
	private JTextField textField_3;
	private JTextField textField_4;
	private JPasswordField passwordField_createAcct;
	private JPasswordField passwordField_login;
	private static JCheckBox chckbxYear;
	private static JCheckBox chckbxGenre ;
	private static JButton btnReserve;
	private static JButton btnInsertMovie;
	private static JButton btnDeleteReservation;
	private static JButton btnInsertCopy; 
	private static JButton btnDeleteCopy;
	private static JButton btnDeleteMovie;
	private static JMenu mnView;
	private static JMenu mnEdit;
	private static JMenu mnTools;
	private JTextField textField_edit1;
	private JTextField textField_edit2;
	private JPasswordField passwordField;
	private JTextField textField_mvTitle;
	private JTextField textField_mvGenre;
	private Choice choice;
	private Choice choice_1;
	private Choice choice_2;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ApplicationWindow window = new ApplicationWindow();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public ApplicationWindow() {
		initialize();
	}

	/**
	 * Initialise the contents of the frame.
	 */
	private void initialize() {
		/** Initialises the database */ 
		dbHandler = new DatabaseHandler();
		dbHandler.getDBConnection();
		
		frame = new JFrame("We Like Movies");
		frame.setBounds(100, 100, 670, 510);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		movieModel = new DefaultListModel();
		movieModel2 = new DefaultListModel();
		avalibleModel = new DefaultListModel();
		resModel = new DefaultListModel();
		copyModel = new DefaultListModel();
		
		frame.getContentPane().setLayout(new CardLayout(0, 0));
		
		frame.setJMenuBar(menuBar);
		
		JMenu mnFile = new JMenu("File");
		menuBar.add(mnFile);
		
		JMenuItem mntmLogout = new JMenuItem("Logout");
		mntmLogout.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				changePanel(LOGINPANEL);
				
				/** Clean up stuff */
				btnDeleteReservation.setVisible(false);
				mnView.setEnabled(false);
				mnEdit.setEnabled(false);
				mnTools.setEnabled(false);
				text_username.setText("");
				passwordField_login.setText("");
			}
		});
		mnFile.add(mntmLogout);
		
		JMenuItem mntmClose = new JMenuItem("Close");
		mntmClose.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				System.exit(0);
			}
		});
		mnFile.add(mntmClose);
		
		mnEdit = new JMenu("Edit");
		mnEdit.setEnabled(false);
		menuBar.add(mnEdit);
		
		JMenuItem mntmCustomerInfo = new JMenuItem("Customer Information");
		mntmCustomerInfo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				changePanel(EDITINFOPANEL);

			}
		});
		mnEdit.add(mntmCustomerInfo);
		
		mnView = new JMenu("View");
		mnView.setEnabled(false);
		menuBar.add(mnView);
		
		JMenuItem mntmMovies = new JMenuItem("Movies");
		mntmMovies.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				changePanel(MOVIESPANEL);
			}
		});
		mnView.add(mntmMovies);
		
		JMenuItem mntmReservations = new JMenuItem("Reservations");
		mntmReservations.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent arg0) {
			changePanel(RESERVATIONSPANEL);
			
			resModel.clear();
			
			try{
				if (isAdmin){
					ResultSet rs = dbHandler.getAllReservations();
					btnDeleteReservation.setVisible(true);
					while( rs.next() ){
						resModel.addElement(new ListElement2(rs.getString(1), rs.getString(2), rs.getString(3), rs.getInt(4), rs.getInt(5)));
					}
					
					rs.close();
				}
				else{
					
					ResultSet rs = dbHandler.getCustomerReservations(customerID);
					while( rs.next() ){
						resModel.addElement(new ListElement3(rs.getString(1), rs.getString(2), rs.getString(3)));
					}
					
					rs.close();						
				}
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
		}
	});
		mnView.add(mntmReservations);
		
		mnTools = new JMenu("Tools");
		mnTools.setEnabled(false);
		menuBar.add(mnTools);
		
		JMenuItem mntmEditMoviesList = new JMenuItem("Insert/Delete Movies");
		mntmEditMoviesList.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				changePanel(EDITMOVIESPANEL);
				
				// Show all movies
				try {
					
					movieModel2.removeAllElements();
					copyModel.removeAllElements();
					ResultSet rs = dbHandler.getMovie("* ", "", "", "", "");
					while ( rs.next() ) {
						movieModel2.addElement(new ListElement(rs.getString(1), rs.getString(2), rs.getString(3)));
						
					}
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				
				
			}
		});
		mnTools.add(mntmEditMoviesList);
		
		
		JMenuItem mntmStats = new JMenuItem("Statistics");
		mntmStats.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String customerNumber = null;
				String avgCopies = null;
				String[] branch = dbHandler.allMovieBranchStat();
				String branchList = Arrays.toString(branch);
				
				
				
				customerNumber = dbHandler.customerStat();
				
				JOptionPane.showMessageDialog(frame,
					    "There are currently " + customerNumber + " customers registered.");
			
				avgCopies = dbHandler.avgCopiesStat();
				
				JOptionPane.showMessageDialog(frame,
					    "On average, there are currently " + avgCopies + " copies of each title that has at least one copy.");
				
				if (branch.length < 1) {
					JOptionPane.showMessageDialog(frame,
						    "There are currently no branches that carry all movies.\n");
				}
				else {
								
					JOptionPane.showMessageDialog(frame,
					    "The following branches carry all movies:\n" 
						 + branchList);
				}
			}
		});
		mnTools.add(mntmStats);
		
		JPanel panel_login = new JPanel();
		frame.getContentPane().add(panel_login, LOGINPANEL);
		panel_login.setLayout(null);
		
		JPanel panel_info = new JPanel();
		panel_info.setBounds(134, 120, 390, 180);
		panel_login.add(panel_info);
		panel_info.setLayout(null);
		
		text_username = new JTextField();
		text_username.setBounds(115, 30, 235, 29);
		panel_info.add(text_username);
		text_username.setColumns(10);
		
		JLabel lblUsername = new JLabel("User ID");
		lblUsername.setFont(new Font("The GodFather", Font.PLAIN, 24));
		lblUsername.setBounds(34, 30, 57, 29);
		panel_info.add(lblUsername);
		
		JLabel lblPassword = new JLabel("Password");
		lblPassword.setFont(new Font("The GodFather", Font.PLAIN, 24));
		lblPassword.setBounds(34, 70, 57, 29);
		panel_info.add(lblPassword);
		
		JButton btnLogin = new JButton("Login");
		btnLogin.setFont(new Font("Walt Disney Script", Font.PLAIN, 20));
		btnLogin.setBounds(152, 133, 89, 29);
		panel_info.add(btnLogin);
		btnLogin.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String username = text_username.getText();
				char[] password = passwordField_login.getPassword();
				boolean isValid;
				
				isValid = dbHandler.validateUser(username, password);
								
				if (!isValid) {
					JOptionPane.showMessageDialog(frame,
							"Please re-enter your Login and Password.",
							"Invalid Login or Password",
						    JOptionPane.ERROR_MESSAGE);
				}
				else {
					mnView.setEnabled(true);
					if (username.equals("1")) {
						isAdmin = true;
						customerID = 1;  
						System.out.println("user is admin");
						mnTools.setEnabled(true);
					}

					else {
						isAdmin = false;
						customerID = Integer.parseInt(username);
						System.out.println("user is " + customerID);
						mnEdit.setEnabled(true);
					}
					changePanel(MOVIESPANEL);
				}
				
			}
		});
		
		passwordField_login = new JPasswordField();
		passwordField_login.setBounds(115, 70, 235, 29);
		panel_info.add(passwordField_login);
		
		JLabel lblWeLikeMovies = new JLabel("We Like Movies. Do you?");
		lblWeLikeMovies.setFont(new Font("Parry Hotter", Font.PLAIN, 36));
		lblWeLikeMovies.setBounds(153, 22, 358, 87);
		panel_login.add(lblWeLikeMovies);
		
		JPanel panel_createAcct = new JPanel();
		panel_createAcct.setBounds(134, 299, 390, 95);
		panel_login.add(panel_createAcct);
		panel_createAcct.setLayout(null);
		
		JLabel lblOr = new JLabel("Or");
		lblOr.setFont(new Font("The GodFather", Font.PLAIN, 24));
		lblOr.setBounds(192, 0, 13, 29);
		panel_createAcct.add(lblOr);
		
		JButton btnSignUp = new JButton("Sign Up");
		btnSignUp.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				changePanel(SIGNUPPANEL);
			}
		});
		btnSignUp.setFont(new Font("Walt Disney Script", Font.PLAIN, 20));
		btnSignUp.setBounds(143, 43, 106, 29);
		panel_createAcct.add(btnSignUp);
		
		JPanel panel_signUp = new JPanel();
		frame.getContentPane().add(panel_signUp, SIGNUPPANEL);
		panel_signUp.setLayout(null);
		
		JPanel panel_contactInfo = new JPanel();
		panel_contactInfo.setBounds(152, 94, 329, 148);
		panel_signUp.add(panel_contactInfo);
		panel_contactInfo.setLayout(null);
		
		JLabel lblFirstName = new JLabel("First Name");
		lblFirstName.setBounds(0, 0, 63, 29);
		panel_contactInfo.add(lblFirstName);
		lblFirstName.setFont(new Font("The GodFather", Font.PLAIN, 24));
		
		textField_1 = new JTextField();
		textField_1.setBounds(94, 0, 235, 29);
		panel_contactInfo.add(textField_1);
		textField_1.setColumns(10);
		
		JLabel lblLastName = new JLabel("Last Name");
		lblLastName.setBounds(0, 40, 59, 29);
		panel_contactInfo.add(lblLastName);
		lblLastName.setFont(new Font("The GodFather", Font.PLAIN, 24));
		
		textField_2 = new JTextField();
		textField_2.setBounds(94, 40, 235, 29);
		panel_contactInfo.add(textField_2);
		textField_2.setColumns(10);
		
		JLabel lblAddress = new JLabel("Address");
		lblAddress.setBounds(0, 79, 63, 29);
		panel_contactInfo.add(lblAddress);
		lblAddress.setFont(new Font("The GodFather", Font.PLAIN, 24));
		
		textField_3 = new JTextField();
		textField_3.setBounds(94, 79, 235, 29);
		panel_contactInfo.add(textField_3);
		textField_3.setColumns(10);
		
		JLabel lblPhoneNumber = new JLabel("Phone Number");
		lblPhoneNumber.setBounds(0, 119, 82, 29);
		panel_contactInfo.add(lblPhoneNumber);
		lblPhoneNumber.setFont(new Font("The GodFather", Font.PLAIN, 24));
		
		textField_4 = new JTextField();
		textField_4.setBounds(94, 119, 235, 29);
		panel_contactInfo.add(textField_4);
		textField_4.setColumns(10);
		
		JPanel panel_userPasswordSign = new JPanel();
		panel_userPasswordSign.setBounds(152, 261, 329, 131);
		panel_signUp.add(panel_userPasswordSign);
		panel_userPasswordSign.setLayout(null);
		
		JLabel lblPassword_1 = new JLabel("Password");
		lblPassword_1.setBounds(0, 40, 82, 29);
		panel_userPasswordSign.add(lblPassword_1);
		lblPassword_1.setFont(new Font("The GodFather", Font.PLAIN, 24));
		
		JLabel lblWeWillProvide = new JLabel("We will provide you a unique User ID");
		lblWeWillProvide.setBounds(99, 0, 220, 29);
		panel_userPasswordSign.add(lblWeWillProvide);
		lblWeWillProvide.setFont(new Font("The GodFather", Font.PLAIN, 24));
		
		passwordField_createAcct = new JPasswordField();
		passwordField_createAcct.setBounds(94, 40, 235, 29);
		panel_userPasswordSign.add(passwordField_createAcct);
		
		JButton button_sign = new JButton("Sign Up");
		button_sign.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String fName = textField_1.getText();
				String lName = textField_2.getText();
				String address = textField_3.getText();
				String phone = textField_4.getText();
				String password = String.valueOf(passwordField_createAcct.getPassword());
				boolean isPhone = true;
					
				for (int i = 0; i < phone.length(); i++) {
					if (phone.charAt(i)=='0'||phone.charAt(i)=='1'||phone.charAt(i)=='2'||phone.charAt(i)=='3'
							||phone.charAt(i)=='4'||phone.charAt(i)=='5'||phone.charAt(i)=='6'||phone.charAt(i)=='7'
							||phone.charAt(i)=='8'||phone.charAt(i)=='9')
						;
					else {
						isPhone = false;
						break;
					}
				}
				
				if (fName.trim().isEmpty() || lName.trim().isEmpty() || 
						address.trim().isEmpty() || phone.trim().isEmpty() || password.isEmpty()) {
					JOptionPane.showMessageDialog(frame,
						    "Please provide all the information requested.",
						    "Incomplete Information",
						    JOptionPane.ERROR_MESSAGE);
				}
				
				else if (phone.length() != 10 || isPhone==false) {
						JOptionPane.showMessageDialog(frame,
							    "Please provide a valid phone number.",
							    "Invalid Phone Number",
							    JOptionPane.ERROR_MESSAGE);
					}
				
				else {
					
						try { 
							String username = dbHandler.insertCustomer(fName + " " + lName, phone, address, password);
							isAdmin = false;
							customerID = Integer.parseInt(username);
							mnView.setEnabled(true);
							JOptionPane.showMessageDialog(frame,
							    "Welcome " + fName +" " + lName + "! \nYou can now login using Login: " 
							    + username + "\nand password: " + password,
							    "Congratulations!",
							    JOptionPane.PLAIN_MESSAGE);
							changePanel(MOVIESPANEL);
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
				
			}
		});
		button_sign.setBounds(151, 102, 106, 29);
		panel_userPasswordSign.add(button_sign);
		button_sign.setFont(new Font("Walt Disney Script", Font.PLAIN, 20));
		
		JLabel lblCreateAnAccount = new JLabel("Create an account!");
		lblCreateAnAccount.setFont(new Font("Parry Hotter", Font.PLAIN, 36));
		lblCreateAnAccount.setBounds(226, 0, 251, 87);
		panel_signUp.add(lblCreateAnAccount);
		
		JPanel panel_editCustomer = new JPanel();
		frame.getContentPane().add(panel_editCustomer, EDITINFOPANEL);
		panel_editCustomer.setLayout(null);
		
		JPanel panel_editableInfo = new JPanel();
		panel_editableInfo.setLayout(null);
		panel_editableInfo.setBounds(153, 98, 329, 148);
		panel_editCustomer.add(panel_editableInfo);
		
		JLabel label_2 = new JLabel("Address");
		label_2.setFont(new Font("The GodFather", Font.PLAIN, 24));
		label_2.setBounds(0, 0, 63, 29);
		panel_editableInfo.add(label_2);
		
		textField_edit1 = new JTextField();
		textField_edit1.setColumns(10);
		textField_edit1.setBounds(94, 0, 235, 29);
		panel_editableInfo.add(textField_edit1);
		
		JLabel label_3 = new JLabel("Phone Number");
		label_3.setFont(new Font("The GodFather", Font.PLAIN, 24));
		label_3.setBounds(0, 40, 82, 29);
		panel_editableInfo.add(label_3);
		
		textField_edit2 = new JTextField();
		textField_edit2.setColumns(10);
		textField_edit2.setBounds(94, 40, 235, 29);
		panel_editableInfo.add(textField_edit2);
		
		JLabel lblPassword_2 = new JLabel("Password");
		lblPassword_2.setFont(new Font("The GodFather", Font.PLAIN, 24));
		lblPassword_2.setBounds(0, 81, 82, 29);
		panel_editableInfo.add(lblPassword_2);
		
		passwordField = new JPasswordField();
		passwordField.setBounds(94, 80, 235, 29);
		panel_editableInfo.add(passwordField);
		
		JLabel lblStep1 = new JLabel("1) Complete each of the following fields. ");
		lblStep1.setFont(new Font("Tahoma", Font.PLAIN, 15));
		lblStep1.setBounds(51, 54, 265, 19);
		panel_editCustomer.add(lblStep1);
		
		JLabel lblStep2 = new JLabel("2) Click the Edit button in order to successfully edit your contact information.");
		lblStep2.setFont(new Font("Tahoma", Font.PLAIN, 15));
		lblStep2.setBounds(51, 243, 497, 19);
		panel_editCustomer.add(lblStep2);
		
		JButton btnEdit = new JButton("Edit");
		btnEdit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String address = textField_edit1.getText();
				String phone = textField_edit2.getText();
				String password = String.valueOf(passwordField.getPassword());
				boolean isPhone = true;
				
				for (int i = 0; i < phone.length(); i++) {
					if (phone.charAt(i)=='0'||phone.charAt(i)=='1'||phone.charAt(i)=='2'||phone.charAt(i)=='3'
							||phone.charAt(i)=='4'||phone.charAt(i)=='5'||phone.charAt(i)=='6'||phone.charAt(i)=='7'
							||phone.charAt(i)=='8'||phone.charAt(i)=='9')
						;
					else {
						isPhone = false;
						break;
					}
				}
				
				System.out.println("phone is: " + phone.trim()+"\n");
				System.out.println("address is: " + address.trim() +"\n");
				System.out.println("password is: " + password.trim() + "\n");
				
				if (phone.trim().isEmpty() || address.trim().isEmpty() || password.trim().isEmpty()) {
					JOptionPane.showMessageDialog(frame,
						    "Please fill every field.",
						    "Incomplete information.",
						    JOptionPane.ERROR_MESSAGE);
				}
				else if (phone.length() != 10 || isPhone==false) {
					System.out.println("phone number entered is :" + phone);
					JOptionPane.showMessageDialog(frame,
						    "Please provide a valid phone number.",
						    "Invalid Phone Number",
						    JOptionPane.ERROR_MESSAGE);
				}
				else {
					try {
						String userID = Integer.toString(customerID);
						dbHandler.updateCustomerInfo(userID, phone, address, password);
						JOptionPane.showMessageDialog(frame,
							    "Your UserID is: " + userID + " and your Password is: " + password,
							    "Congratulations!",
							    JOptionPane.PLAIN_MESSAGE);
						changePanel(MOVIESPANEL);
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		});
		btnEdit.setFont(new Font("Walt Disney Script", Font.PLAIN, 20));
		btnEdit.setBounds(250, 298, 89, 23);
		panel_editCustomer.add(btnEdit);
		
		JPanel panel_reservations = new JPanel();
		frame.getContentPane().add(panel_reservations, RESERVATIONSPANEL);
		panel_reservations.setLayout(null);
		
		JScrollPane scrollPane_2 = new JScrollPane();
		scrollPane_2.setBounds(192, 109, 382, 229);
		panel_reservations.add(scrollPane_2);
		
		resList = new JList(resModel);
		scrollPane_2.setViewportView(resList);
		
		btnDeleteReservation = new JButton("Delete Reservation");
		btnDeleteReservation.setVisible(false);
		btnDeleteReservation.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				ListElement2 selected = (ListElement2) resList.getSelectedValue();
				
				if (selected != null) {
				
					try {
	
						dbHandler.deleteReservations(selected.rID);
						dbHandler.setCopyStatus(selected.copyID, "TRUE");
						resModel.removeAllElements();
						ResultSet rs = dbHandler.getAllReservations();
						while ( rs.next() ) {
							System.out.println(rs.getString(1) + rs.getString(2) + rs.getString(3)); //TEST!
							
							resModel.addElement(new ListElement2(rs.getString(1), rs.getString(2), rs.getString(3), rs.getInt(4), rs.getInt(5)));
							
						}
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		});
		btnDeleteReservation.setBounds(18, 109, 144, 23);
		panel_reservations.add(btnDeleteReservation);
		
		JLabel lblReservations = new JLabel("Reservations");
		lblReservations.setFont(new Font("Parry Hotter", Font.PLAIN, 24));
		lblReservations.setBounds(321, 40, 116, 58);
		panel_reservations.add(lblReservations);
		
		JPanel panel_movies = new JPanel();
		frame.getContentPane().add(panel_movies, MOVIESPANEL);
		panel_movies.setLayout(null);
		
		final JPanel panel_search = new JPanel();
		panel_search.setBounds(0, 0, 207, 231);
		panel_movies.add(panel_search);
		panel_search.setLayout(null);
		
		textField = new JTextField("Movie Title");
		textField.setBounds(10, 32, 187, 20);
		panel_search.add(textField);
		textField.setColumns(10);
		
		choice_1 = new Choice();
		choice_1.setBounds(10, 90, 187, 20);
		
		choice_1.addItem("All Genres");
		
		choice = new Choice();
		choice.setBounds(10, 58, 187, 20);
		choice.addItem("All Years");
		panel_search.add(choice);
		
		panel_search.add(choice_1);
		
		JCheckBox chckbxTitle = new JCheckBox("Title");
		chckbxTitle.setFont(new Font("Tahoma", Font.PLAIN, 10));
		chckbxTitle.setEnabled(false);
		chckbxTitle.setSelected(true);
		chckbxTitle.setBounds(10, 141, 45, 23);
		panel_search.add(chckbxTitle);
		
		chckbxYear = new JCheckBox("Year");
		chckbxYear.setFont(new Font("Tahoma", Font.PLAIN, 10));
		chckbxYear.setBounds(109, 141, 47, 23);
		panel_search.add(chckbxYear);
		
		chckbxGenre = new JCheckBox("Genre");
		chckbxGenre.setFont(new Font("Tahoma", Font.PLAIN, 10));
		chckbxGenre.setBounds(109, 167, 67, 23);
		panel_search.add(chckbxGenre);
		movieList = new JList(movieModel);
		
		JLabel lblSearchBy = new JLabel("Search by:");
		lblSearchBy.setBounds(10, 6, 67, 17);
		panel_search.add(lblSearchBy);
		lblSearchBy.setFont(new Font("Tahoma", Font.PLAIN, 14));
		
		JButton btnSearch = new JButton("Search");
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
				try {
					String title;
					String year;
					String genre;
					
					if (textField.getText().equals("Movie Title")){
						title = "";
					} else {
						title = textField.getText();
					}
					if (choice.getSelectedItem().equals("All Years")){
						year = "";
					} else{
						year = choice.getSelectedItem();
					}
					if (choice_1.getSelectedItem().equals("All Genres")){
						genre = "";
					} else{
						genre = choice_1.getSelectedItem();
					}
					
					String select = DatabaseHandler.MOVIE_TITLE + ", " + DatabaseHandler.MOVIE_YEAR;
					
					if (chckbxGenre.isSelected()) {
						select += ", " + DatabaseHandler.MOVIE_GENRE;
					}
					
					movieModel.clear();
					ResultSet rs = dbHandler.getMovie(select, title, year, genre, "");
					
					while( rs.next() ){
					
						if (chckbxGenre.isSelected()){
							movieModel.addElement(new ListElement(rs.getString(1), rs.getString(2), rs.getString(3)));
						}
						else {
							movieModel.addElement(new ListElement(rs.getString(1), rs.getString(2), ""));
						}
					}
					
					rs.close();
					
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		});
		
		btnSearch.setBounds(10, 208, 75, 23);
		panel_search.add(btnSearch);
		
		JButton btnReset = new JButton("Reset");
		btnReset.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				textField.setText("Movie Title");
				choice.select(0);
				choice_1.select(0);
				movieModel.clear();
				avalibleModel.clear();
				btnReserve.setEnabled(false);
			}
		});
		btnReset.setBounds(111, 208, 75, 23);
		panel_search.add(btnReset);
		
		JLabel lblShow = new JLabel("Show:");
		lblShow.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblShow.setBounds(10, 117, 39, 17);
		panel_search.add(lblShow);
		
		movieList.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent arg0) {
				
				if (!arg0.getValueIsAdjusting()){
					lblStarring.setVisible(false);
					lblAwardsWon.setVisible(false);
					JList list = (JList)arg0.getSource();
					
					ListElement selected = (ListElement) list.getSelectedValue();
					
					if (selected != null){
						try {
							ResultSet rs2 = dbHandler.getActor(selected.title, selected.year);
							while(rs2.next()){
								lblStarring.setText("Starring: " +rs2.getString(1));
								lblStarring.setVisible(true);
							}
						} catch (SQLException e) {
							e.printStackTrace();
						}	
						try {
							ResultSet rs3 = dbHandler.getAward(selected.title, selected.year);
							lblAwardsWon.setVisible(false);
							if (rs3 != null){ 
								while(rs3.next()){
									lblAwardsWon.setText("Award won: " +rs3.getString(1).trim() + ", For: " +rs3.getString(2).trim() + ", " +rs3.getString(3).trim());
									lblAwardsWon.setVisible(true);
								}
							}
						} catch (SQLException e) {
							e.printStackTrace();
						}	

						avalibleModel.clear();
						btnReserve.setEnabled(false);
						try {
							
							ResultSet rs = dbHandler.getAvailability(selected.title, selected.year);
							
							while ( rs.next() ) {
								System.out.println(rs.getString(1) + rs.getString(2) + rs.getString(3)); //TEST!
								
								avalibleModel.addElement(new AvailableListElement(rs.getString(1), rs.getString(2), rs.getInt(3)));
								
							}
							rs.close();
							System.out.println("-------");
							
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
				}
				
			}
		});
		movieList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		JScrollPane scrollPane = new JScrollPane(movieList);
		scrollPane.setBounds(217, 0, 421, 209);
		panel_movies.add(scrollPane);
		scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		
		avalibleList = new JList(avalibleModel);
		avalibleList.setBounds(194, 292, 444, 148);
		
		JScrollPane scrollPane_1 = new JScrollPane(avalibleList);
		scrollPane_1.setBounds(217, 276, 421, 148);
		panel_movies.add(scrollPane_1);
		scrollPane_1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		avalibleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		avalibleList.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent arg0) {
				
				if (!arg0.getValueIsAdjusting()){
					JList list = (JList)arg0.getSource();
					
					AvailableListElement selected = (AvailableListElement) list.getSelectedValue();
					
					if (selected != null){
						btnReserve.setEnabled(true);
					}
				}
				
			}
		});

		
		lblStarring = new JLabel("Starring: ");
		lblStarring.setBounds(217, 214, 421, 28);
		panel_movies.add(lblStarring);
		lblStarring.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
		lblStarring.setVisible(false);
		
		btnReserve = new JButton("Reserve");
		btnReserve.setFont(new Font("Tahoma", Font.PLAIN, 14));
		btnReserve.setBounds(56, 337, 101, 25);
		panel_movies.add(btnReserve);
		btnReserve.setEnabled(false);
		
		lblAwardsWon = new JLabel("Awards Won: ");
		lblAwardsWon.setFont(new Font("Dialog", Font.PLAIN, 15));
		lblAwardsWon.setBounds(217, 247, 421, 28);
		panel_movies.add(lblAwardsWon);
		lblAwardsWon.setVisible(false);
		
		JPanel panel_editMovies = new JPanel();
		frame.getContentPane().add(panel_editMovies, EDITMOVIESPANEL);
		panel_editMovies.setLayout(null);
		
		JPanel panel_editMovie = new JPanel();
		panel_editMovie.setBorder(new TitledBorder(null, "Movies", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_editMovie.setBounds(23, 0, 593, 230);
		panel_editMovies.add(panel_editMovie);
		panel_editMovie.setLayout(null);
		
		JScrollPane scroll_editMovies = new JScrollPane((Component) null);
		scroll_editMovies.setBounds(134, 28, 450, 156);
		panel_editMovie.add(scroll_editMovies);
		scroll_editMovies.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		
		movieList2 = new JList((ListModel) movieModel2);
		movieList2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		scroll_editMovies.setViewportView(movieList2);
		
		movieList2.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent arg0) {
				
				if (!arg0.getValueIsAdjusting()){
					JList list = (JList)arg0.getSource();
					
					ListElement selected = (ListElement) list.getSelectedValue();
					
					if (selected != null){

						btnDeleteCopy.setEnabled(false);
						btnInsertCopy.setEnabled(false);
						copyModel.clear();
						btnDeleteMovie.setEnabled(true);
				
						try {
							
							ResultSet rs = dbHandler.getAllLocations();
							
							while ( rs.next() ) {
								
								copyModel.addElement(new AvailableListElement(rs.getString(1), rs.getString(2),
										dbHandler.getNumberOfCopies(selected.title, selected.year, rs.getString(1), rs.getString(2))));
								
							}
							rs.close();
							System.out.println("-------");
							
						} catch (SQLException e) {
							e.printStackTrace();
						}
						
						
					}
					
				}
				
			}
		});
		
		btnInsertMovie = new JButton("Insert");
		btnInsertMovie.setEnabled(true);
		btnInsertMovie.setBounds(10, 189, 89, 23);
		panel_editMovie.add(btnInsertMovie);
		btnInsertMovie.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try{
					String title;
					String year;
					String genre;
					
					if (!textField.getText().equals("Movie title") && !choice_2.getSelectedItem().equals("Year") && !textField_mvGenre.getText().equals("Genre") ){
						
						title = textField_mvTitle.getText();
						year = choice_2.getSelectedItem();
						genre = textField_mvGenre.getText();
						dbHandler.insertMovie(title, year, genre);
						
						textField_mvTitle.setText("Movie title");
						textField_mvGenre.setText("Genre");
						choice_2.select(0);
					} 	
					movieModel2.removeAllElements();
					ResultSet rs = dbHandler.getMovie( "*", "", "", "", "");
				
						while( rs.next() ){
							movieModel2.addElement(new ListElement(rs.getString(1), rs.getString(2), rs.getString(3)));
							}
						rs.close();
					
					} catch (SQLException e) {
						e.printStackTrace();
				}
			}
		});
		
		
		btnDeleteMovie = new JButton("Delete");
		btnDeleteMovie.setEnabled(false);
		btnDeleteMovie.setBounds(10, 92, 89, 23);
		panel_editMovie.add(btnDeleteMovie);
		btnDeleteMovie.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				ListElement selectedM = (ListElement) movieList2.getSelectedValue();
			
				
				if (selectedM != null) {
					
					try {
						String deleteResponse = dbHandler.deleteMovie(selectedM.title, selectedM.year);
						
						if (deleteResponse.equals("Cannot delete Movie - Reservation found.")) {
							JOptionPane.showMessageDialog(frame,
									"Cannot delete Movie - Reservation found.",
									"ERROR - CANNOT DELETE MOVIE",
								    JOptionPane.ERROR_MESSAGE);
						}
						else {
							movieModel2.clear();
							copyModel.clear();
							JOptionPane.showMessageDialog(frame,
								    deleteResponse);
							ResultSet rs = dbHandler.getMovie("* ", "", "", "", "");
							while ( rs.next() ) {
								movieModel2.addElement(new ListElement(rs.getString(1), rs.getString(2), rs.getString(3)));
								
							}
							rs.close();
							
						}
						
						btnDeleteMovie.setEnabled(false);
						
					} catch (SQLException e) {
						
						e.printStackTrace();
					}
				}
			}
		});
		
		
		
		textField_mvTitle = new JTextField("Movie Title");
		textField_mvTitle.setBounds(134, 190, 187, 20);
		panel_editMovie.add(textField_mvTitle);
		
		choice_2 = new Choice();
		choice_2.addItem("Year");
		choice_2.setBounds(368, 190, 58, 20);
		panel_editMovie.add(choice_2);
		
		textField_mvGenre = new JTextField("Genre");
		textField_mvGenre.setBounds(476, 190, 108, 20);
		panel_editMovie.add(textField_mvGenre);
		
		JPanel panel_editCopies = new JPanel();
		panel_editCopies.setBounds(23, 235, 593, 215);
		panel_editMovies.add(panel_editCopies);
		panel_editCopies.setLayout(null);
		panel_editCopies.setBorder(new TitledBorder(null, "Copies", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		JScrollPane scroll_editCopies = new JScrollPane((Component) null);
		scroll_editCopies.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		scroll_editCopies.setBounds(134, 28, 450, 156);
		panel_editCopies.add(scroll_editCopies);
		
		copyList = new JList((ListModel) copyModel);
		copyList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		scroll_editCopies.setViewportView(copyList);
		copyList.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent arg0) {
				
				if (!arg0.getValueIsAdjusting()){
					
					btnInsertCopy.setEnabled(true);
					btnDeleteCopy.setEnabled(true);
				}
				
			}
		});
		
		btnInsertCopy = new JButton("Insert");
		btnInsertCopy.setEnabled(false);
		btnInsertCopy.setBounds(10, 69, 89, 23);
		panel_editCopies.add(btnInsertCopy);
		btnInsertCopy.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				ListElement selectedM = (ListElement) movieList2.getSelectedValue();
				AvailableListElement selectedC = (AvailableListElement) copyList.getSelectedValue();
				
				if (selectedM != null && selectedC != null) {
					
					try {
						dbHandler.insertCopy(selectedM.title, selectedM.year, selectedM.genre, selectedC.location, selectedC.city);
						
						
						copyModel.clear();
						
						try {
							
							ResultSet rs = dbHandler.getAllLocations();
							
							while ( rs.next() ) {
								
								copyModel.addElement(new AvailableListElement(rs.getString(1), rs.getString(2),
										dbHandler.getNumberOfCopies(selectedM.title, selectedM.year, rs.getString(1), rs.getString(2))));
								
							}
							rs.close();
							System.out.println("-------");
							
						} catch (SQLException e) {
							e.printStackTrace();
						}
						
					} catch (SQLException e) {
						e.printStackTrace();
					}
					
				}
				btnInsertCopy.setEnabled(false);
				btnDeleteCopy.setEnabled(false);
				
			}
		});
		
		btnDeleteCopy = new JButton("Delete");
		btnDeleteCopy.setEnabled(false);
		btnDeleteCopy.setBounds(10, 125, 89, 23);
		panel_editCopies.add(btnDeleteCopy);
		btnDeleteCopy.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				AvailableListElement selected = (AvailableListElement) copyList.getSelectedValue();
				ListElement selectedM = (ListElement) movieList2.getSelectedValue();
				
				if (selected != null && selectedM != null) {
				
					try {
						int cId = dbHandler.getMinCopyId(selected.location, selected.city, selectedM.title, selectedM.year);
						dbHandler.deleteCopy(cId);
						
						copyModel.clear();
						
						try {
							
							ResultSet rs = dbHandler.getAllLocations();
							
							while ( rs.next() ) {
								copyModel.addElement(new AvailableListElement(rs.getString(1), rs.getString(2),
										dbHandler.getNumberOfCopies(selectedM.title, selectedM.year, rs.getString(1), rs.getString(2))));
								
							}
							rs.close();
							System.out.println("-------");
							
						} catch (SQLException e) {
							e.printStackTrace();
						}
						
						
					} catch (SQLException e) {
						
						e.printStackTrace();
					}
				}
				
				btnInsertCopy.setEnabled(false);
				btnDeleteCopy.setEnabled(false);
			}
		});
		
	
		btnReserve.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				AvailableListElement selected = (AvailableListElement) avalibleList.getSelectedValue();
				ListElement selectedM = (ListElement) movieList.getSelectedValue();
				
				if (selected != null && selectedM != null) {
				
					try {
						int cId = dbHandler.getMinCopyId(selected.location, selected.city, selectedM.title, selectedM.year);
						dbHandler.insertReservation(customerID, cId);
						dbHandler.setCopyStatus(cId, "FALSE");
						avalibleModel.removeAllElements();
						
						ResultSet rs = dbHandler.getAvailability(selectedM.title, selectedM.year);
						
						while ( rs.next() ) {
							System.out.println(rs.getString(1) + rs.getString(2) + rs.getString(3)); //TEST!
							
							avalibleModel.addElement(new AvailableListElement(rs.getString(1), rs.getString(2), rs.getInt(3)));
							
						}
						rs.close();
						
						btnReserve.setEnabled(false);
						
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		});
		
		for (int i=2012; i>1950; i--){
			choice.addItem(String.valueOf(i));
			choice_2.addItem(String.valueOf(i));
		}
		
		choice_2.select(0);
		
		try {
			ResultSet rs = dbHandler.getAllGenres();
			
			while( rs.next() ) {
				choice_1.addItem(rs.getString(1));
			}
			
			rs.close();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public JTextField getTextField() {
		return textField;
	}
	
	
	/**
	 * Class used in the movie list so we can get a handle on the title and year of the movie
	 * @author Emil
	 *
	 */
	private class ListElement{
		String title;
		String year;
		String genre;
		
		public ListElement(String t, String y, String g) {
			title = t.trim();
			year = y.trim();
			genre = g.trim();
		}
		
		public String toString(){
			if (chckbxYear.isSelected()){
				return title + ", " + year + ". " + genre;
			}
			else {
				return title + ". " + "" + " " + genre;
			}
		}
		
		
	}
	
	private class ListElement2{
		String name;
		String date;
		String title;
		int rID;
		int copyID;
		
	public ListElement2(String n, String t, String d, int r, int c) {
		name = n.trim();
		title = t.trim();
		date = d.trim();
		rID = r;
		copyID = c;
	}
	
	public String toString(){
		return name + " reserved " + title + " to " + date;
	}
	
	}
	
	private class ListElement3{
		String location;
		String date;
		String title;
		
		public ListElement3(String t, String d, String l) {
			location = l.trim();
			title = t.trim();
			date = d.trim();
		}
		
		public String toString(){
			return title + " from " + location + " to " + date;
		}
		
	}
	
	/**
	 * Class used in the available list so we can get a handle on the location and city of 
	 * @author Emil
	 *
	 */
	private class AvailableListElement{
		String location;
		String city;
		int availableN;
		
		public AvailableListElement(String l, String c, int n) {
			location = l.trim();
			city = c.trim();
			availableN = n;
		}
		
		public String toString(){
			return location + ", " + city + " - Available copies: " + availableN + ".";
		}
	}
	
	private void changePanel(String panel) {
		// Change the panel...
		CardLayout cl = (CardLayout)frame.getContentPane().getLayout();
		cl.show(frame.getContentPane(), panel);
		
		try {
			
			choice_1.removeAll();
			choice_1.addItem("All Genres");
			ResultSet rs = dbHandler.getAllGenres();
			
			while( rs.next() ) {
				choice_1.addItem(rs.getString(1));
			}
			
			rs.close();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		// ...and reset EVERYTHING
		textField.setText("Movie Title");
		textField_mvTitle.setText("Movie Title");
		textField_mvGenre.setText("Genre");
		choice.select(0);
		choice_1.select(0);
		choice_2.select(0);
		movieModel.clear();
		movieModel2.clear();
		avalibleModel.clear();
		resModel.clear();
		btnReserve.setEnabled(false);
		text_username.setText("");
		textField_edit1.setText("");
		textField_edit2.setText("");
		textField.setText("Movie Title");
		textField_1.setText("");
		textField_2.setText("");
		textField_3.setText("");
		textField_4.setText("");
		passwordField.setText("");
		passwordField_createAcct.setText("");
		passwordField_login.setText("");
		chckbxGenre.setSelected(false);
		chckbxYear.setSelected(false);
		lblStarring.setVisible(false);
		lblAwardsWon.setVisible(false);
		System.out.println("Change");
		
	}

}
